from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from ..core.database import get_db
from ..core.dependencies import get_current_admin_user, get_current_active_user
from ..models.user import User
from ..schemas.module import Module, ModuleCreate, ModuleUpdate, AdminModulesResponse, ModuleTree
from ..services.module_service import ModuleService

router = APIRouter(prefix="/modules", tags=["modules"])

@router.get("/", response_model=List[Module])
def get_modules(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    """获取所有模块列表（仅管理员可访问）"""
    module_service = ModuleService(db)
    return module_service.get_modules(skip, limit)

@router.get("/tree", response_model=AdminModulesResponse)
def get_module_tree(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取模块树结构（用于导航菜单）"""
    module_service = ModuleService(db)
    
    # 如果是管理员，返回完整的模块树
    if current_user.is_superuser:
        modules = module_service.get_admin_modules()
        return AdminModulesResponse(data=modules)
    
    # 对于普通用户，也返回所有激活的模块（可以根据实际需求调整权限控制）
    modules = module_service.get_module_tree()
    return AdminModulesResponse(data=modules)

@router.get("/{module_id}", response_model=Module)
def get_module(
    module_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    """获取指定模块信息（仅管理员可访问）"""
    module_service = ModuleService(db)
    module = module_service.get_module(module_id)
    if not module:
        raise HTTPException(
            status_code=404,
            detail="模块不存在"
        )
    return module

@router.post("/", response_model=Module)
def create_module(
    module: ModuleCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    """创建新模块（仅管理员可访问）"""
    module_service = ModuleService(db)
    return module_service.create_module(module)

@router.put("/{module_id}", response_model=Module)
def update_module(
    module_id: int,
    module: ModuleUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    """更新模块信息（仅管理员可访问）"""
    module_service = ModuleService(db)
    return module_service.update_module(module_id, module)

@router.delete("/{module_id}")
def delete_module(
    module_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    """删除模块（仅管理员可访问）"""
    module_service = ModuleService(db)
    module_service.delete_module(module_id)
    return {"message": "模块删除成功"}

@router.get("/admin", response_model=AdminModulesResponse)
def get_admin_modules(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    """获取管理员可访问的模块列表（仅管理员可访问）"""
    module_service = ModuleService(db)
    modules = module_service.get_admin_modules()
    return AdminModulesResponse(data=modules)